var pie = {
  id:'pie',
  serverBase:'http://192.168.14.1/',
  dpi:1,
  originHeight:null,
  originWidth:null,
  headerHeight:44,
  maxWidth:400,
  height:null,
  width:null,
  localData:null,
  curPageId:null,
  confirmShow:false,
  isTeacher:false,
  loadingShow:false,
  loading:null,
  remindDisapear:null,
  labelArray:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
  questionList:null,
  makeTeamList:null,
  atAsk:false,
  refreshStart:false,
  refreshReady:null,
  onInput:false,
  curInputId:null,
  tcp:{
    handle:null,
    dumped:false,
    checkSend:null,
    lastTime:null,
    connected:false,
    autoAccount:null,
    autoPassword:null,
    init:function(){
      pie.showLoading('正在连接')
      this.handle = io.connect(pie.serverBase);
      var Handle = this.handle;
      Handle.on('connected',function(){
        pie.hideLoading();
        pie.tcp.connected = true;
        pie.hideLoading();
        if(pie.tcp.autoAccount&&pie.tcp.autoPassword){
          pie.tcp.login(pie.tcp.autoAccount,pie.tcp.autoPassword);
        }
        if(pie.isTeacher){
          pie.tcp.logAdmin();
        }
        pie.tcp.getQuestionList();
        Handle.on('regError',function(data){
          if(pie.atAsk){
            pie.hideLoading();
            pie.atAsk = false;
            alert('注册失败:'+data.text);
          }
        });
        Handle.on('loginError',function(data){
          if(pie.atAsk){
            pie.hideLoading();
            pie.atAsk = false;
            delete localStorage.tmpAccount;
            delete localStorage.tmpPassword;
            delete localStorage.pieUserAccount;
            delete localStorage.pieUserPassword;
            alert('登录失败:'+data.text);
          }
        });
        Handle.on('loginSuccess',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.user.info = data;
            pie.user.init();
            if(localStorage.tmpAccount&&localStorage.tmpPassword){
              localStorage.pieUserAccount = localStorage.tmpAccount;
              localStorage.pieUserPassword = localStorage.tmpPassword
              delete localStorage.tmpAccount;
              delete localStorage.tmpPassword;
            }
            pie.showPage('coursePage');
            pie.tcp.getQuestionList();
          }
        });
        Handle.on('changeInfoSuccess',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.user.info = data;
            pie.user.init();
            pie.showPage('settingPage');
          }
        });
        Handle.on('questionList',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.page.coursePage.initQuestion(data);
            pie.endRefresh();
            pie.tcp.getTeamList();
          }
        });
        Handle.on('submitPutQuestionSuccess',function(){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('发布问题成功');
            jQuery('#putQuestionPage input').val('');
            jQuery('#putQuestionPage textarea').val('');
            jQuery('#makeTeamPage input').val('');
            jQuery('#makeTeamPage textarea').val('');
            pie.showPage('coursePage');
            pie.tcp.getQuestionList();
          }
        });
        Handle.on('submitMakeTeamSuccess',function(){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('发布组队成功');
            jQuery('#putQuestionPage input').val('');
            jQuery('#putQuestionPage textarea').val('');
            jQuery('#makeTeamPage input').val('');
            jQuery('#makeTeamPage textarea').val('');
            pie.showPage('coursePage');
            pie.tcp.getQuestionList();
          }
        });
        Handle.on('doQuestionSuccess',function(data){
          if(pie.atAsk){
            var qNum = pie.questionList.length;
            for(var i = 0; i < qNum; i++){
              if(pie.questionList[i]._id == data._id){
                pie.questionList[i] = data;
                break;
              }
            }
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('回答问题成功');
            var lp = pie.page.lookQuestionPage;
            lp.setup(lp.curQuestionId);
          }
        });
        Handle.on('restartQuestionSuccess',function(data){
          if(pie.atAsk){
            var qNum = pie.questionList.length;
            for(var i = 0; i < qNum; i++){
              if(pie.questionList[i]._id == data._id){
                pie.questionList[i] = data;
                break;
              }
            }
            pie.atAsk = false;
            pie.hideLoading();
            alert('提问'+data.title+'已经重新开始作答');
            var lp = pie.page.lookQuestionPage;
            lp.setup(lp.curQuestionId);
          }
        });
        Handle.on('restartMakeTeamSuccess',function(data){
          pie.atAsk = false;
          pie.hideLoading();
          alert('组队'+data.title+'已经重新开始');
          var mNum = pie.makeTeamList.length;
          var rId = -1;
          for(var i = 0; i < mNum; i++){
            if(pie.makeTeamList[i]._id == data._id){
              pie.makeTeamList[i] = data;
              rId = i;
              break;
            }
          }
          if(pie.curPageId == 'lookMakeTeamPage'){
            var lp = pie.page.lookMakeTeamPage;
            if(lp.curMakeTeamId == rId){
              lp.setup(rId);
            }
          }
        });
        Handle.on('refreshChoicesSuccess',function(data){
          if(pie.atAsk){
            var qNum = pie.questionList.length;
            for(var i = 0; i < qNum; i++){
              if(pie.questionList[i]._id == data._id){
                pie.questionList[i] = data;
                break;
              }
            }
            pie.atAsk = false;
            pie.hideLoading();
            var lp = pie.page.lookQuestionPage;
            lp.setup(lp.curQuestionId);
          }
        });
        Handle.on('doQuestionRepeat',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('重复答题,你是黑客吧?');
          }
        });
        Handle.on('stopQuestionSuccess',function(data){
          if(pie.atAsk){
            var qNum = pie.questionList.length;
            for(var i = 0; i < qNum; i++){
              if(pie.questionList[i]._id == data._id){
                pie.questionList[i] = data;
                break;
              }
            }
            pie.atAsk = false;
            pie.hideLoading();
            alert('提问"'+data.title+'"已经结束作答');
            var lp = pie.page.lookQuestionPage;
            lp.setup(lp.curQuestionId);
          }
        });
        Handle.on('teamList',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.page.coursePage.initTeam(data);
          }
        });
        Handle.on('signUpSuccess',function(data){
          if(pie.atAsk){
            var mNum = pie.makeTeamList.length;
            for(var i = 0; i < mNum; i++){
              if(pie.makeTeamList[i]._id == data._id){
                pie.makeTeamList[i] = data;
                break;
              }
            }
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('报名成功');
            var lp = pie.page.lookMakeTeamPage;
            lp.setup(lp.curMakeTeamId);
          }
        });
        Handle.on('signUpRepeat',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('重复报名,你是黑客吧?');
          }
        });
        Handle.on('createGroupSuccess',function(data){
          if(pie.atAsk){
            var mNum = pie.makeTeamList.length;
            for(var i = 0; i < mNum; i++){
              if(pie.makeTeamList[i]._id == data._id){
                pie.makeTeamList[i] = data;
                break;
              }
            }
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('创建队伍成功');
            var lp = pie.page.lookMakeTeamPage;
            lp.setup(lp.curMakeTeamId);
          }
        });
        Handle.on('createGroupError',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            alert('创建队伍失败,原因是:'+data.message);
          }
        });
        Handle.on('systemError',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            pie.remind('系统错误');
          }
        });
        Handle.on('dump',function(){
          if(pie.tcp.dumped){return;}
          pie.tcp.dumped = true;
          alert('你的账号已在别处登录');
          pie.user.logout(0);
        });
        Handle.on('targetInfo',function(data){
          var len = data.length;
          for(var i = 0; i < len; i++){
            jQuery('.'+data[i].account+'Nickname').html(data[i].name);
          }
          pie.page.lookMakeTeamPage.scrollArea.refresh();
        });
        Handle.on('makeJoinRequestSuccess',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            alert('组队请求已经成功发出,请等待队长回应');
          }
        });
        Handle.on('makeJoinRequestError',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            alert('组队请求发送失败,原因是:'+data.message);
          }
        });
        Handle.on('joinRequest',function(data){
          var str = data.requestNickname+'请求加入您在'+data.makeTeamTitle+'组队中的队伍,点击确认同意该请求';
          if(confirm(str)){
            pie.tcp.agreeJoinRequest(data);
          }
        });
        Handle.on('acceptJoinRequestError',function(data){
          alert('同意组队请求失败,原因是:'+data.message);
        });
        Handle.on('joinRequestFailed',function(data){
          alert('请求组队失败,原因是:'+data.message);
        });
        Handle.on('joinRequestAccepted',function(reply){
          alert(reply.message);
          var data = reply.makeTeamInfo;
          var mNum = pie.makeTeamList.length;
          var rId = -1;
          for(var i = 0; i < mNum; i++){
            if(pie.makeTeamList[i]._id == data._id){
              pie.makeTeamList[i] = data;
              rId = i;
              break;
            }
          }
          if(pie.curPageId == 'lookMakeTeamPage'){
            var lp = pie.page.lookMakeTeamPage;
            if(lp.curMakeTeamId == rId){
              lp.setup(rId);
            }
          }
        });
        Handle.on('makeTeamInfo',function(data){
          pie.atAsk = false;
          pie.endRefresh();
          var mNum = pie.makeTeamList.length;
          var rId = -1;
          for(var i = 0; i < mNum; i++){
            if(pie.makeTeamList[i]._id == data._id){
              pie.makeTeamList[i] = data;
              rId = i;
              break;
            }
          }
          if(pie.curPageId == 'lookMakeTeamPage'){
            var lp = pie.page.lookMakeTeamPage;
            if(lp.curMakeTeamId == rId){
              lp.setup(rId);
            }
          }
        });
        Handle.on('groupDissolved',function(data){
          pie.hideLoading();
          alert('你在'+data.title+'组队中的队伍已经被解散了');
          var mNum = pie.makeTeamList.length;
          var rId = -1;
          for(var i = 0; i < mNum; i++){
            if(pie.makeTeamList[i]._id == data._id){
              pie.makeTeamList[i] = data;
              rId = i;
              break;
            }
          }
          if(pie.curPageId == 'lookMakeTeamPage'){
            var lp = pie.page.lookMakeTeamPage;
            if(lp.curMakeTeamId == rId){
              lp.setup(rId);
            }
          }
        });
        Handle.on('exitGroupSuccess',function(data){
          if(pie.atAsk){
            pie.atAsk = false;
            pie.hideLoading();
            alert('你已退出了在'+data.title+'组队中的队伍');
            var mNum = pie.makeTeamList.length;
            var rId = -1;
            for(var i = 0; i < mNum; i++){
              if(pie.makeTeamList[i]._id == data._id){
                pie.makeTeamList[i] = data;
                rId = i;
                break;
              }
            }
            if(pie.curPageId == 'lookMakeTeamPage'){
              var lp = pie.page.lookMakeTeamPage;
              if(lp.curMakeTeamId == rId){
                lp.setup(rId);
              }
            }
          }
        });
        Handle.on('memberExit',function(reply){
          alert(reply.message);
          var data = reply.info;
          var mNum = pie.makeTeamList.length;
          var rId = -1;
          for(var i = 0; i < mNum; i++){
            if(pie.makeTeamList[i]._id == data._id){
              pie.makeTeamList[i] = data;
              rId = i;
              break;
            }
          }
          if(pie.curPageId == 'lookMakeTeamPage'){
            var lp = pie.page.lookMakeTeamPage;
            if(lp.curMakeTeamId == rId){
              lp.setup(rId);
            }
          }
        });
        Handle.on('makeTeamFinished',function(data){
          pie.hideLoading();
          alert(data.title+'的组队已经结束');
          var mNum = pie.makeTeamList.length;
          var rId = -1;
          for(var i = 0; i < mNum; i++){
            if(pie.makeTeamList[i]._id == data._id){
              pie.makeTeamList[i] = data;
              rId = i;
              break;
            }
          }
          if(pie.curPageId == 'lookMakeTeamPage'){
            var lp = pie.page.lookMakeTeamPage;
            if(lp.curMakeTeamId == rId){
              lp.setup(rId);
            }
          }
        });
        Handle.on('disconnect',function(){
          if(pie.tcp.dumped){return;}
          pie.tcp.connected = false;
          pie.tcp.handle = null;
          pie.tcp.init();
        });
      });
    },
    autologin:function(account,password){
      pie.showLoading('正在连接网络');
      this.autoAccount = account;
      this.autoPassword = password;
      this.init();
    },
    login:function(account,password){
      if(!this.handle){
        pie.remind('网络连接失败,请稍后再试');
      }
      else{
        pie.showLoading('正在登录');
        pie.atAsk = true;
        localStorage.tmpAccount = myEncode(account);
        localStorage.tmpPassword = myEncode(password);
        pie.tcp.handle.emit('login',{
          'account':account,
          'password':password
        });
      }
    },
    register:function(name,account,password,sex){
      if(!this.handle){
        pie.remind('网络连接失败,请稍后再试');
      }
      else{
        pie.atAsk = true;
        pie.showLoading('正在注册');
        pie.tcp.handle.emit('register',{
          'name':name,
          'account':account,
          'password':password,
          'sex':sex
        });
      }
    },
    logAdmin:function(){
      if(this.handle){
        pie.atAsk = true;
        this.handle.emit('admin');
      }
    },
    getQuestionList:function(){
      if(this.handle){
        pie.atAsk = true;
        this.handle.emit('getQuestionList');
      }
    },
    submitPutQuestion:function(title,array,flag){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('submitPutQuestion',{'title':title,'array':array,'flag':flag});
      }
    },
    submitMakeTeam:function(title,array){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('submitMakeTeam',{'title':title,'array':array});
      }
    },
    doQuestion:function(questionId,choiceArray){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('doQuestion',{'_id':pie.questionList[questionId]._id,'choiceArray':choiceArray});
      }
    },
    stopAndShowResult:function(questionId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('stopQuestion',{'_id':pie.questionList[questionId]._id});
      }
    },
    doSignUp:function(makeTeamId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('doSignUp',{'_id':pie.makeTeamList[makeTeamId]._id});
      }
    },
    refreshChoices:function(questionId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在刷新');
        this.handle.emit('refreshChoices',{'_id':questionId});
      }
    },
    restartQuestion:function(questionId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('restartQuestion',{'_id':pie.questionList[questionId]._id});
      }
    },
    restartMakeTeam:function(makeTeamId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('restartMakeTeam',{'_id':pie.makeTeamList[makeTeamId]._id});
      }
    },
    getTeamList:function(){
      if(this.handle){
        pie.atAsk = true;
        this.handle.emit('getTeamList');
      }
    },
    getTargetInfo:function(targetArray){
      if(this.handle){
        this.handle.emit('getTargetInfo',targetArray);
      }
    },
    changeName:function(name){
      if(!this.handle){
        pie.remind('网络连接失败,请稍后再试');
      }
      else{
        pie.showLoading('正在提交');
        pie.atAsk = true;
        pie.tcp.handle.emit('changeName',{
          'newName':name
        });
      }
    },
    judgeTime:function(mTime){
      var timeArray = mTime.split(' ');
      var dateArray = timeArray[0].split('-');
      var clockArray = timeArray[1].split(':');
      var curTime = new Date();
      var result = null;
      if(dateArray[0]<curTime.getFullYear()||dateArray[1]<curTime.getMonth()+1){
        result = mTime;
      }
      else{
        if(dateArray[2]<curTime.getDate()){
          result = dateArray[1]+'-'+dateArray[2]+' '+clockArray.join(':');
        }
        else{
          result = clockArray.join(':');
        }
      }
      return result;
    },
    createGroup:function(makeTeamId,choiceId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('createGroup',{'_id':pie.makeTeamList[makeTeamId]._id,'choiceId':choiceId});
      }
    },
    joinGroup:function(makeTeamId,choiceId,groupId){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        this.handle.emit('joinGroup',{'_id':pie.makeTeamList[makeTeamId]._id,'choiceId':choiceId,'groupId':groupId});
      }
    },
    agreeJoinRequest:function(data){
      if(this.handle){
        this.handle.emit('agreeJoinRequest',data);
      }
    },
    refreshMakeTeam:function(makeTeamId){
      if(this.handle){
        pie.atAsk = true;
        this.handle.emit('refreshMakeTeam',{'_id':pie.makeTeamList[makeTeamId]._id});
      }
    },
    dissolveGroup:function(){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        var makeTeamId = pie.page.lookMakeTeamPage.curMakeTeamId;
        this.handle.emit('dissolveGroup',{'_id':pie.makeTeamList[makeTeamId]._id});
      }
    },
    exitGroup:function(){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        var makeTeamId = pie.page.lookMakeTeamPage.curMakeTeamId;
        this.handle.emit('exitGroup',{'_id':pie.makeTeamList[makeTeamId]._id});
      }
    },
    stopMakeTeam:function(){
      if(this.handle){
        pie.atAsk = true;
        pie.showLoading('正在提交');
        var makeTeamId = pie.page.lookMakeTeamPage.curMakeTeamId;
        this.handle.emit('stopMakeTeam',{'_id':pie.makeTeamList[makeTeamId]._id});
      }
    }
  },
  localNotification:{
    add:function(title,content){
      if(pie.platform == 'android'){
        window.plugins.statusBarNotification.notify(title,content);
      }
    }
  },
  user:{
    info:null,
    init:function(){
      if(this.info.sex == 1){
        jQuery('#userInfoItemSex .userInfoItemValue span').html('男');
        jQuery('#userInfoItemSex i').addClass('icon-male');
      }
      else{
        jQuery('#userInfoItemSex .userInfoItemValue span').html('女');
        jQuery('#userInfoItemSex i').addClass('icon-female');
      }
      if(this.info.role == 1){
        jQuery('#userInfoItemRole .userInfoItemValue span').html('学生');
      }
      else{
        jQuery('#userInfoItemRole .userInfoItemValue span').html('教师');
      }
      jQuery('#userInfoItemName .userInfoItemValue span').html(this.info.name);
      jQuery('#userInfoNameInput').val(this.info.name);
      jQuery('#userAvatarAccountInput').val(this.info.account);
      var vImg = new Image();
      vImg.onload = function(){
        jQuery('#userAvatar').attr('src',this.src);
        var maxSize = 100;
        if(this.height>this.width){
          var cc = this.width/maxSize;
          var newHeight = this.height/cc;
          jQuery('#uploadAvatarButton').css('width',maxSize);
          jQuery('#uploadAvatarButton').css('height',newHeight);
          jQuery('#userAvatar').css('width',maxSize);
          jQuery('#userAvatar').css('height',newHeight);
        }
        else{
          var cc = this.height/maxSize;
          var newWidth = this.width/cc;
          jQuery('#uploadAvatarButton').css('width',newWidth);
          jQuery('#uploadAvatarButton').css('height',maxSize);
          jQuery('#userAvatar').css('width',newWidth);
          jQuery('#userAvatar').css('height',maxSize);
        }
        var sa = pie.page.settingPage.scrollArea;
        if(sa){
          sa.refresh();
        }
        this.src = null;
      }
      if(this.info.avatar){
        vImg.src = this.info.avatar;
      }
      else{
        vImg.src = 'img/uploadPhoto.png';
      }
    },
    logout:function(needCheck){
      if(needCheck){
        pie.confirm('确认要退出么?',this.doLogout)
      }
      else{
        this.doLogout();
      }
    },
    doLogout:function(){
      delete localStorage.pieUserAccount;
      delete localStorage.pieUserPassword;
      window.location.reload();
    }
  },
  page:{
    loginPage:{
      id:'loginPage',
      backPageId:'guidePage',
      needScroll:true,
      scrollArea:null,
      headerExist:true,
      leftMenu:'返回',
      title:'登录',
      init:function(){},
      submit:function(){
        var account = jQuery('#loginAccountInput').val();
        if(account == ''){
          pie.remind('请输入账号');
          jQuery('#loginAccountInput').focus();
          return;
        }
        var password = jQuery('#loginPasswordInput').val();
        if(password == ''){
          pie.remind('请输入密码');
          jQuery('#loginPasswordInput').focus();
          return;
        }
        pie.tcp.login(account,password);
      }
    },
    regPage:{
      id:'regPage',
      backPageId:'guidePage',
      needScroll:true,
      scrollArea:null,
      headerExist:true,
      curSex:1,
      title:'注册',
      leftMenu:'返回',
      inited:false,
      init:function(){
      },
      chooseSex:function(n){
        this.curSex = n;
        if(n){
          jQuery('#chooseMale').css('color','rgb(9, 172, 165)');
          jQuery('#chooseFemale').css('color','#aaa');
        }
        else{
          jQuery('#chooseFemale').css('color','rgb(255, 40, 49)');
          jQuery('#chooseMale').css('color','#aaa');
        }
      },
      submit:function(){
        var name = jQuery('#regNameInput').val();
        if(name == ''){
          pie.remind('请输入姓名');
          jQuery('#regNameInput').focus();
          return;
        }
        var account = jQuery('#regAccountInput').val();
        if(account == ''){
          pie.remind('请输入账号');
          jQuery('#regAccountInput').focus();
          return;
        }
        var password = jQuery('#regPasswordInput').val();
        if(password == ''){
          pie.remind('请输入密码');
          jQuery('#regPasswordInput').focus();
          return;
        }
        var sex = this.curSex;
        pie.tcp.register(name,account,password,sex);
      }
    },
    findBackPasswordPage:{
      id:'findBackPasswordPage',
      backPageId:'loginPage',
      needScroll:true,
      scrollArea:null,
      headerExist:true,
      title:'找回密码',
      leftMenu:'返回',
      init:function(){}
    },
    inputPage:{
      id:'inputPage',
      backPageId:'settingPage',
      needScroll:true,
      scrollArea:null,
      headerExist:true,
      title:'输入',
      leftMenu:'取消',
      inputType:null,
      curMobile:null,
      init:function(){},
      showInput:function(item){
        jQuery('.infoEditArea').css('display','none');
        switch(item){
          case 'name':
          this.title = '姓名';
          this.inputType = 0;
          jQuery('#userInfoNameEditArea').css('display','block');
          break;
        }
        pie.showPage(this.id);
      },
      submit:function(){
        switch(this.inputType){
          case 0:this.editName();break;
        }
      },
      editName:function(){
        var newName = jQuery('#userInfoNameInput').val();
        if(newName == ''){
          pie.remind('姓名不能为空');
          return;
        }
        pie.tcp.changeName(newName);
      }
    },
    coursePage:{
      id:'coursePage',
      backPageId:null,
      needScroll:true,
      needRefresh:true,
      scrollArea:null,
      headerExist:true,
      leftMenu:'',
      title:'课程',
      intied:false,
      refreshTimes:0,
      refresh:function(){
        console.log('coursePage refresh:'+this.refreshTimes);
        this.refreshTimes++;
        pie.tcp.getQuestionList();
      },
      init:function(){},
      initQuestion:function(data){
        pie.questionList = data;
        var questionNum = data.length;
        var questionHtml = '';
        for(var i = 0; i < questionNum; i++){
          questionHtml += "<div id='"+i+"question' class='existQuestion'><div class='questionTitleArea'>提问:"
          +data[i].title+"</div><div class='questionChoiceArea'>";
          var curChoiceArray = data[i].choices;
          var choiceNum = curChoiceArray.length;
          for(var j = 0; j < choiceNum; j++){
            questionHtml += "<div class='questionChoice'><div class='choiceContent'>"+pie.labelArray[j]
            +":&nbsp&nbsp"+curChoiceArray[j].text+"</div></div>";
          }
          questionHtml += "</div></div>";
        }
        jQuery('#existQuestionArea').html(questionHtml);
        for(var i = 0; i < questionNum; i++){
          Quo('#'+i+'question').unbind('tap');
          Quo('#'+i+'question').bind('tap',function(){
            var questionId = parseInt(this.id);
            pie.showPage('lookQuestionPage');
            pie.page.lookQuestionPage.setup(questionId);
          })
        }
        this.scrollArea.refresh();
      },
      initTeam:function(data){
        pie.makeTeamList = data;
        var makeTeamNum = data.length;
        var makeTeamHtml = '';
        for(var i = 0; i < makeTeamNum; i++){
          makeTeamHtml += "<div id='"+i+"makeTeam' class='existMakeTeam'><div class='makeTeamTitleArea'>组队:"
          +data[i].title+"</div><div class='makeTeamChoiceArea'>";
          var curChoiceArray = data[i].choices;
          var choiceNum = curChoiceArray.length;
          for(var j = 0; j < choiceNum; j++){
            makeTeamHtml += "<div class='makeTeamChoice'><div class='choiceContent'>"+pie.labelArray[j]
            +":&nbsp&nbsp"+curChoiceArray[j].text+"</div></div>";
          }
          makeTeamHtml += "</div></div>";
        }
        jQuery('#existMakeTeamArea').html(makeTeamHtml);
        for(var i = 0; i < makeTeamNum; i++){
          Quo('#'+i+'makeTeam').unbind('tap');
          Quo('#'+i+'makeTeam').bind('tap',function(){
            var makeTeamId = parseInt(this.id);
            pie.showPage('lookMakeTeamPage');
            pie.page.lookMakeTeamPage.setup(makeTeamId);
          })
        }
        this.scrollArea.refresh();
      }
    },
    settingPage:{
      id:'settingPage',
      backPageId:'coursePage',
      needScroll:true,
      scrollArea:null,
      title:'设置',
      leftMenu:'返回',
      headerExist:true,
      init:function(){},
      refresh:function(){
      },
      uploadPhoto:function(files){
        var imageMode = /^[\s\S]+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$/;
        if(!imageMode.test(files[0].name)){
          pie.remind('请上传png,jpg,peg,gif,bmp格式的图像');
          return;
        }
        var form = document.getElementById('uploadPhotoForm');
        var action = pie.serverBase+'/upload';
        var xhr = new XMLHttpRequest();
        pie.showLoading('正在上传头像');
        xhr.onreadystatechange = function(){
          if(xhr.readyState == 4){
            if(xhr.status == 200){
              pie.hideLoading();
              var reply = jQuery.parseJSON(xhr.responseText);
              if(reply.status == 'success'){
                pie.user.info.avatar = reply.src;
                pie.user.init();
              }
              else{
                pie.remind('上传头像失败');
              }
            }
          }
        }
        xhr.open('POST',action);
        xhr.send(new FormData(form));
      }
    },
    putQuestionPage:{
      id:'putQuestionPage',
      backPageId:'coursePage',
      needScroll:true,
      scrollArea:null,
      title:'提问',
      leftMenu:'返回',
      headerExist:true,
      curChoiceIndex:0,
      curChoiceNum:1,
      init:function(){},
      addChoice:function(){
        if(this.curChoiceIndex == this.curChoiceNum-1){
          this.curChoiceNum++;
          this.curChoiceIndex++;
          var newChoice = document.createElement('div');
          newChoice.id = 'putQuestionChoice'+this.curChoiceIndex;
          var newLabel = pie.labelArray[this.curChoiceIndex];
          newChoice.innerHTML = "<div class='questionLabel'>请输入选项"+newLabel+"</div>"
          +"<textarea></textarea><input type='checkbox'>";
          document.getElementById('putQuestionChoiceArea').appendChild(newChoice);
        }
        else{
          this.curChoiceIndex++;
          jQuery('#putQuestionChoice'+this.curChoiceIndex).css('display','block');
        }
        this.scrollArea.refresh();
      },
      deleteChoice:function(){
        if(this.curChoiceIndex<0){return;}
        jQuery('#putQuestionChoice'+this.curChoiceIndex).css('display','none');
        this.curChoiceIndex--;
        this.scrollArea.refresh();
      },
      submit:function(){
        var title = jQuery('#putQuestionTitleArea textarea').val();
        var choiceArray = [];
        var flagArray = [];
        var trueExist = false;
        for(var i = 0; i <= this.curChoiceIndex; i++){
          var tmp = jQuery('#putQuestionChoice'+i+' textarea').val();
          var ff = document.querySelector('#putQuestionChoice'+i+' input').checked;
          if(ff){
            trueExist = true;
          }
          choiceArray.push(tmp);
          flagArray.push(ff);
        }
        if(choiceArray.length<2||!trueExist){
          alert('请编辑至少两个选项并包含至少一个正确选项');
          return;
        }
        pie.tcp.submitPutQuestion(title,choiceArray,flagArray);
      }
    },
    lookQuestionPage:{
      id:'lookQuestionPage',
      backPageId:'coursePage',
      needScroll:true,
      scrollArea:null,
      title:'查看问题',
      leftMenu:'返回',
      headerExist:true,
      curQuestionId:0,
      curQuestionDone:false,
      choiceArray:null,
      init:function(){},
      setup:function(id){
        this.curQuestionId = id;
        this.choiceArray = [];
        if(id < 0||id > pie.questionList.length-1){alert('error');return;}
        var curQuestion = pie.questionList[id];
        jQuery('#doQuestionButton').css('display','none');
        var curChoiceArray = curQuestion.choices;
        var choiceNum = curChoiceArray.length;
        var choiceHtml = '';
        this.curQuestionDone = false;
        var userSelect = '';
        for(var j = 0; j < choiceNum; j++){
          choiceHtml += "<div id='"+j+"editableChoice' class='editableChoice'><span class='choiceContent'>"+pie.labelArray[j]+":&nbsp&nbsp"+curChoiceArray[j].text
          +"</span></div>";
          if(!pie.isTeacher){
            var curQuestionChoice = curChoiceArray[j].students.find(pie.user.info.account);
            if(curQuestionChoice >= 0){
              this.curQuestionDone = true;
              userSelect += pie.labelArray[j];
            }
          }
        }
        var tHtml = '问题:&nbsp&nbsp'+curQuestion.title;
        if(!pie.isTeacher&&curQuestion.finished){
          tHtml += "(已经结束作答,正确答案是:"
          for(var i = 0; i < choiceNum; i++){
            if(curChoiceArray[i].flag){
              tHtml += pie.labelArray[i];
            }
          }
          tHtml += ")";
        }
        jQuery('#curQuestionTitle').html(tHtml);
        jQuery('#curQuestionChoiceArea').html(choiceHtml);
        if(pie.isTeacher){
          this.showResult();
          return;
        }
        if(this.curQuestionDone){
          jQuery('#studentChoiceArea').html('你已选择了'+userSelect+'选项');
        }
        else if(!curQuestion.finished){
          jQuery('#doQuestionButton').css('display','block');
          jQuery('#studentChoiceArea').html('');
          for(var j = 0; j < choiceNum; j++){
            Quo('#'+j+"editableChoice").unbind('tap');
            Quo('#'+j+"editableChoice").bind('tap',function(){
              var choiceId = parseInt(this.id);
              var lp = pie.page.lookQuestionPage;
              var ca = lp.choiceArray;
              var index = ca.find(choiceId);
              if(index>=0){
                lp.choiceArray = ca.slice(0,index).concat(ca.slice(index+1));
                jQuery(this).removeClass('selectedChoice');
              }
              else{
                ca.push(choiceId);
                jQuery(this).addClass('selectedChoice');
              }
            });
          }
        }
        this.scrollArea.refresh();
      },
      showResult:function(){
        jQuery('#lookResultArea').css('display','block');
        var myData = [];
        var curQuestion = pie.questionList[this.curQuestionId];
        var curChoiceArray = curQuestion.choices;
        var choiceNum = curChoiceArray.length;
        var resultHtml = '正确答案是';
        var rightArray = [];
        for(var i = 0; i < choiceNum; i++){
          if(curChoiceArray[i].flag){
            resultHtml += pie.labelArray[i];
          }
        }
        var as = curQuestion.allStudents.length;
        resultHtml += ',当前共有'+as+'人作答';
        if(as>0){
          for(var i = 0; i < as; i++){
            var isRight = true;
            var curAccount = curQuestion.allStudents[i];
            for(var j = 0; j < choiceNum; j++){
              if(curChoiceArray[j].flag){
                if(curChoiceArray[j].students.find(curAccount)<0){
                  isRight = false;
                  break;
                }
              }
              else{
                if(curChoiceArray[j].students.find(curAccount)>=0){
                  isRight = false;
                  break;
                }
              }
            }
            if(isRight){
              rightArray.push(curAccount);
            }
          }
          resultHtml +=',其中回答正确的人数为'+rightArray.length;
        }
        jQuery('#resultText').html(resultHtml);
        if(curQuestion.finished){
          jQuery('#showResultButton').html('清空数据重新开始作答');
          Quo('#showResultButton').unbind('tap');
          Quo('#showResultButton').bind('tap',function(){
            pie.page.lookQuestionPage.restart();
          });
        }
        else{
          jQuery('#showResultButton').html('停止作答并公布正确答案');
          Quo('#showResultButton').unbind('tap');
          Quo('#showResultButton').bind('tap',function(){
            pie.page.lookQuestionPage.stopAndShowResult();
          });
        }
        for(var i = 0; i < choiceNum; i++){
          var thisChoice = curChoiceArray[i];
          var tmp = [];
          tmp.push(pie.labelArray[i]);
          tmp.push(thisChoice.students.length);
          myData.push(tmp);
        }
        var allColors = ['#AF0202', '#EC7A00', '#FCD200', '#81C714','#ea4c89','#d34f32'];
        var colors = allColors.slice(0,choiceNum);
        var barChart = new JSChart('barResultArea', 'bar');
        barChart.setDataArray(myData);
        barChart.colorizeBars(colors);
        barChart.setTitle(' ');
        barChart.setTitleColor('#8E8E8E');
        barChart.setAxisNameX('');
        barChart.setAxisNameY('%');
        barChart.setAxisColor('#C4C4C4');
        barChart.setAxisNameFontSize(16);
        barChart.setAxisNameColor('#999');
        barChart.setAxisValuesColor('#7E7E7E');
        barChart.setBarValuesColor('#7E7E7E');
        barChart.setAxisPaddingTop(20);
        barChart.setAxisPaddingBottom(20);
        barChart.setTitleFontSize(11);
        barChart.setBarBorderWidth(1);
        barChart.setBarBorderColor('#C4C4C4');
        barChart.setBarSpacingRatio(50);
        barChart.setGrid(false);
        barChart.setSize(pie.width, 300);
        barChart.draw();
        var pieChart = new JSChart('pieResultArea', 'pie');
        pieChart.setDataArray(myData);
        pieChart.colorizePie(colors);
        pieChart.setTitle(' ');
        pieChart.setTitleColor('#8E8E8E');
        pieChart.setTitleFontSize(11);
        pieChart.setTextPaddingTop(30);
        pieChart.setSize(pie.width,300);
        pieChart.setPieRadius(130);
        pieChart.setPieUnitsColor('#555');
        pieChart.draw();
        this.scrollArea.refresh();
      },
      restart:function(){
        pie.tcp.restartQuestion(this.curQuestionId);
      },
      refreshChoices:function(){
        var _id = pie.questionList[this.curQuestionId]._id;
        pie.tcp.refreshChoices(_id);
      },
      stopAndShowResult:function(){
        pie.tcp.stopAndShowResult(this.curQuestionId);
      },
      doQuestion:function(){
        if(!this.choiceArray||this.choiceArray.length<1){
          alert('请选择至少一个选项');
          return;
        }
        var ss = '';
        this.choiceArray.sort(function(a,b){
          return a-b;
        });
        for(var i = 0; i < this.choiceArray.length; i++){
          ss += pie.labelArray[this.choiceArray[i]];
        }
        pie.confirm("你确认要选择"+ss+"吗？只能提交一次回答",function(){
          var lp = pie.page.lookQuestionPage;
          pie.tcp.doQuestion(lp.curQuestionId,lp.choiceArray);
        });
      }
    },
    makeTeamPage:{
      id:'makeTeamPage',
      backPageId:'coursePage',
      needScroll:true,
      scrollArea:null,
      title:'发起组队',
      leftMenu:'返回',
      headerExist:true,
      curChoiceIndex:0,
      curChoiceNum:1,
      init:function(){},
      addChoice:function(){
        if(this.curChoiceIndex == this.curChoiceNum-1){
          this.curChoiceNum++;
          this.curChoiceIndex++;
          var newChoice = document.createElement('div');
          newChoice.id = 'makeTeamChoice'+this.curChoiceIndex;
          var newLabel = pie.labelArray[this.curChoiceIndex];
          newChoice.innerHTML = "<div class='makeTeamLabel'>请输入选项"+newLabel+"的描述</div>"
          +"<textarea></textarea><div class='makeTeamLabel'>请输入选项"+newLabel+"的队伍总量要求</div>"
          +"<input type='text' class='minGroupNum'>&nbsp到&nbsp<input type='text' class='maxGroupNum'>&nbsp队"
          +"<div class='makeTeamLabel'>请输入选项"+newLabel+"的队伍人数要求</div>"
          +"<input type='text' class='minStudentNum'>&nbsp到&nbsp<input type='text' class='maxStudentNum'>&nbsp人";
          document.getElementById('makeTeamChoiceArea').appendChild(newChoice);
        }
        else{
          this.curChoiceIndex++;
          jQuery('#makeTeamChoice'+this.curChoiceIndex).css('display','block');
        }
        this.scrollArea.refresh();
      },
      deleteChoice:function(){
        if(this.curChoiceIndex<0){return;}
        jQuery('#makeTeamChoice'+this.curChoiceIndex).css('display','none');
        this.curChoiceIndex--;
        this.scrollArea.refresh();
      },
      submit:function(){
        var title = jQuery('#makeTeamTitleArea textarea').val();
        var choiceArray = [];
        for(var i = 0; i <= this.curChoiceIndex; i++){
          var tmp = {
            groups:[],
            text:jQuery('#makeTeamChoice'+i+' textarea').val(),
            minGroupNum:jQuery('#makeTeamChoice'+i+' .minGroupNum').val(),
            maxGroupNum:jQuery('#makeTeamChoice'+i+' .maxGroupNum').val(),
            minStudentNum:jQuery('#makeTeamChoice'+i+' .minStudentNum').val(),
            maxStudentNum:jQuery('#makeTeamChoice'+i+' .maxStudentNum').val()
          }
          choiceArray.push(tmp);
        }
        pie.tcp.submitMakeTeam(title,choiceArray);
      }
    },
    lookMakeTeamPage:{
      id:'lookMakeTeamPage',
      backPageId:'coursePage',
      needScroll:true,
      needRefresh:true,
      scrollArea:null,
      title:'查看组队',
      leftMenu:'返回',
      headerExist:true,
      curMakeTeamId:0,
      alreadySignUp:false,
      alreadyInGroup:false,
      refreshTimes:0,
      init:function(){},
      refresh:function(){
        console.log('makeTeamRefresh here :'+this.refreshTimes);
        this.refreshTimes++;
        pie.tcp.refreshMakeTeam(this.curMakeTeamId);
      },
      setup:function(id){
        this.curMakeTeamId = id;
        if(id < 0||id > pie.makeTeamList.length-1){alert('error');return;}
        var curMakeTeam = pie.makeTeamList[id];
        jQuery('#curMakeTeamTitle').html('组队:&nbsp&nbsp'+curMakeTeam.title+'<span id="signUpStatus"></span>');
        this.judgeSignUp();
        var curChoiceArray = curMakeTeam.choices;
        var choiceNum = curChoiceArray.length;
        var choiceHtml = '';
        for(var j = 0; j < choiceNum; j++){
          choiceHtml += "<div id='"+j+"MakeTeamChoice' class='makeTeamChoice'>"
          +"<div class='choiceContent'>"+pie.labelArray[j]+":&nbsp&nbsp"
          +curChoiceArray[j].text+"</div><div class='makeTeamChoiceStatus'>"
          +"要求队伍数为"+curChoiceArray[j].minGroupNum+'~'+curChoiceArray[j].maxGroupNum
          +"队,每支队伍人数为"+curChoiceArray[j].minStudentNum+'~'+curChoiceArray[j].maxStudentNum
          +"人</div><div class='makeTeamChoiceGroupArea'>";
          var allGroup = curChoiceArray[j].groups;
          var gNum = allGroup.length;
          for(var k = 0; k < gNum; k++){
            choiceHtml += "<div class='makeTeamChoiceGroup'>";
            var curStudents = allGroup[k].students;
            var sNum = curStudents.length;
            var inGroup = false;
            var isLeader = false;
            if(!pie.isTeacher&&curStudents[0] == pie.user.info.account){
              inGroup = true;
              isLeader = true;
              choiceHtml += "<span class='"+curStudents[0]+"Nickname userSelf'></span>(队长)";
            }
            else{
              choiceHtml += "<span class='"+curStudents[0]+"Nickname'></span>(队长)";
            }
            for(var h = 1; h < sNum; h++){
              if(!pie.isTeacher&&curStudents[h] == pie.user.info.account){
                inGroup = true;
                choiceHtml += ",<span class='"+curStudents[h]+"Nickname userSelf'></span>";
              }
              else{
                choiceHtml += ",<span class='"+curStudents[h]+"Nickname'></span>";
              }
            }
            if(!curMakeTeam.finished&&!pie.isTeacher&&!this.alreadyInGroup&&sNum<curChoiceArray[j].maxStudentNum){
              choiceHtml += "<span class='joinGroup' choiceIndex='"+j+"' groupIndex='"+k+"'>申请加入</span>"
            }
            if(!curMakeTeam.finished&&inGroup){
              if(isLeader){
                choiceHtml += "<span id='dissolveGroup'>解散队伍</span>";
              }
              else{
                choiceHtml += "<span id='exitGroup'>退出队伍</span>";
              }
            }
            choiceHtml += "</div>";
          }
          if(!curMakeTeam.finished&&!pie.isTeacher&&gNum < curChoiceArray[j].maxGroupNum&&!this.alreadyInGroup){
            choiceHtml += "<div id='"+j+"createGroup' class='createGroup'>创建队伍</div>";
          }
          choiceHtml += "</div></div>";
        }
        jQuery('#curMakeTeamChoiceArea').html(choiceHtml);
        this.scrollArea.refresh();
        pie.tcp.getTargetInfo(curMakeTeam.allStudents);
        if(pie.isTeacher){
          this.showStop();
          return;
        }
        if(curMakeTeam.finished){return;}
        Quo('.createGroup').unbind('tap');
        Quo('.createGroup').bind('tap',function(){
          pie.page.lookMakeTeamPage.createGroup(parseInt(this.id));
        });
        Quo('.joinGroup').unbind('tap');
        Quo('.joinGroup').bind('tap',function(){
          var ci = this.getAttribute('choiceIndex');
          var gi = this.getAttribute('groupIndex');
          pie.page.lookMakeTeamPage.joinGroup(ci,gi);
        });
        Quo('#dissolveGroup').unbind('tap');
        Quo('#dissolveGroup').bind('tap',function(){
          if(confirm('确认要解散队伍吗?')){
            pie.tcp.dissolveGroup();
          }
        });
        Quo('#exitGroup').unbind('tap');
        Quo('#exitGroup').bind('tap',function(){
          if(confirm('确认要退出队伍吗?')){
            pie.tcp.exitGroup();
          }
        });
      },
      showStop:function(){
        var curMakeTeam = pie.makeTeamList[this.curMakeTeamId];
        jQuery('#stopMakeTeamArea').css('display','block');
        if(curMakeTeam.finished){
          jQuery('#stopMakeTeamButton').html('清空数据重新开始组队');
          Quo('#stopMakeTeamButton').unbind('tap');
          Quo('#stopMakeTeamButton').bind('tap',function(){
            pie.page.lookMakeTeamPage.restart();
          });
          return;
        }
        Quo('#stopMakeTeamButton').unbind('tap');
        Quo('#stopMakeTeamButton').bind('tap',function(){
          pie.tcp.stopMakeTeam();
        });
      },
      judgeSignUp:function(){
        this.alreadyInGroup = false;
        var curMakeTeam = pie.makeTeamList[this.curMakeTeamId];
        var choiceNum = curMakeTeam.choices.length;
        var okArray = [];
        for(var i = 0; i < choiceNum; i++){
          var groupNum = curMakeTeam.choices[i].groups.length;
          for(var j = 0; j < groupNum; j++){
            okArray = okArray.concat(curMakeTeam.choices[i].groups[j].students);
          }
        }
        if(!pie.isTeacher&&okArray.find(pie.user.info.account)>=0){
          this.alreadyInGroup = true;
        }
        var leftArray = diffArray(curMakeTeam.allStudents,okArray);
        if(!leftArray){alert('error');return;}
        var leftNum = leftArray.length;
        var statusHtml = '当前共有'+curMakeTeam.allStudents.length+'人报名,其中还有'
        +leftNum+'人尚无组队';
        if(leftNum>0){
          statusHtml += ':'
        }
        jQuery('#curMakeTeamStatus').html(statusHtml);
        var leftHtml = '';
        if(!pie.isTeacher&&leftArray[0] == pie.user.info.account){
          leftHtml += "<span class='"+leftArray[0]+"Nickname userSelf'></span>";
        }
        else{
          leftHtml += "<span class='"+leftArray[0]+"Nickname'></span>";
        }
        for(var i = 1; i < leftNum; i++){
          if(!pie.isTeacher&&leftArray[i] == pie.user.info.account){
            leftHtml += "&nbsp,&nbsp<span class='"+leftArray[i]+"Nickname userSelf'></span>";
          }
          else{
            leftHtml += "&nbsp,&nbsp<span class='"+leftArray[i]+"Nickname'></span>";
          }
        }
        jQuery('#curMakeTeamLeftStudents').html(leftHtml);
        if(curMakeTeam.finished){
          jQuery('#signUpStatus').html('组队结束!');
          jQuery('#signUpStatus').removeClass('notSignUp alreadySignUp');
          jQuery('#signUpStatus').addClass('finished');
          Quo('#signUpStatus').unbind('tap');
          return;
        }
        if(pie.isTeacher){return;}
        var signUp = curMakeTeam.allStudents.find(pie.user.info.account);
        if(signUp>=0){
          this.alreadySignUp = true;
          jQuery('#signUpStatus').html('报名成功!');
          jQuery('#signUpStatus').removeClass('notSignUp');
          jQuery('#signUpStatus').addClass('alreadySignUp');
          Quo('#signUpStatus').unbind('tap');
        }
        else{
          this.alreadySignUp = false;
          jQuery('#signUpStatus').html('立即报名');
          jQuery('#signUpStatus').removeClass('alreadySignUp');
          jQuery('#signUpStatus').addClass('notSignUp');
          Quo('#signUpStatus').unbind('tap');
          Quo('#signUpStatus').bind('tap',function(){
            pie.tcp.doSignUp(pie.page.lookMakeTeamPage.curMakeTeamId);
          })
        }
      },
      createGroup:function(choiceId){
        if(!this.alreadySignUp){
          pie.confirm('创建队伍需要先报名这次组队,点击确认可以立即报名,报名成功之后请再次点击创建队伍的按钮',function(){
            pie.tcp.doSignUp(pie.page.lookMakeTeamPage.curMakeTeamId);
          });
        }
        else{
          pie.tcp.createGroup(this.curMakeTeamId,choiceId);
        }
      },
      joinGroup:function(choiceIndex,groupIndex){
        var curMakeTeam = pie.makeTeamList[this.curMakeTeamId];
        var groupId = curMakeTeam.choices[choiceIndex].groups[groupIndex]._id;
        if(!this.alreadySignUp){
          pie.confirm('申请入队需要先报名这次组队,点击确认可以立即报名,报名成功之后请再次申请入队',function(){
            pie.tcp.doSignUp(pie.page.lookMakeTeamPage.curMakeTeamId);
          });
        }
        else{
          pie.tcp.joinGroup(this.curMakeTeamId,choiceIndex,groupId);
        }
      },
      restart:function(){
        pie.tcp.restartMakeTeam(this.curMakeTeamId);
      }
    },
    guidePage:{
      id:'guidePage',
      needScroll:true,
      scrollArea:null,
      headerExist:false,
      init:function(){}
    }
  },
  teacherInit:function(){
    jQuery('#coursePageRightMenu').html('');
    jQuery('#teacherArea').css('display','block');
    jQuery('#lookResultArea').css('display','block');
    pie.tcp.init();
  },
  init:function(){
    this.resize();
    this.handleEvent();
    if(this.isTeacher){
      this.showPage('coursePage');
      this.teacherInit();
    }
    else{
      this.showPage('guidePage');
      if(localStorage&&localStorage.pieUserAccount&&localStorage.pieUserPassword){
        var account = myDecode(localStorage.pieUserAccount);
        var password = myDecode(localStorage.pieUserPassword);
        if(account&&password){
          this.tcp.autologin(account,password);
        }
        else{
          pie.tcp.init();
        }
      }
      else{
        pie.tcp.init();
      }
    }
  },
  resize:function(){
    if(!('innerHeight' in window)){
      //为了兼容ie浏览器,此处需要对window.innerHeight做兼容
    }
    if(this.onInput){
      if(window.innerHeight>=this.originHeight){
        jQuery('#'+this.curInputId).blur();
      }
      return;
    }
    this.height = window.innerHeight;
    this.width = Math.min(this.maxWidth,window.innerWidth);
    if(!this.originHeight){
      this.originHeight = this.height;
      this.originWidth = this.width;
    }
    jQuery('#pieHeader').css('height',this.headerHeight);
    jQuery('#pie').css('width',this.width);
    jQuery('#pie').css('height',this.height);

    /*guidePage*/
    jQuery('#loginNav').css('width',(this.width-100)/2);
    jQuery('#regNav').css('width',(this.width-100)/2);
    /*guidePage*/

    /*pieLoading*/
    jQuery('#pieLoading').css('top',Math.floor((this.height-102)/2));
    jQuery('#pieLoading').css('left',Math.floor((this.width-102)/2));
    /*pieLoading*/
  },
  handleEvent:function(){
    /*document.oncontextmenu = function(){
      event.returnValue = false;
    };*/
    if(this.platform != 'ios'){
      jQuery(window).resize(function(){
        pie.resize();
      });
    }
    this.bindEvent('#loginNav','tap',this,'showPage','loginPage');
    this.bindEvent('#regNav','tap',this,'showPage','regPage');
    this.bindEvent('#pageLeftMenu','tap',this,'pageBack');
    this.bindEvent('#loginPageRightMenu','tap',this,'showPage','findBackPasswordPage');
    this.bindEvent('#inputPageRightMenu','tap',this.page.inputPage,'submit');
    this.bindEvent('#coursePageRightMenu','tap',this,'showPage','settingPage');
    this.bindEvent('#loginSubmit','tap',this.page.loginPage,'submit');
    this.bindEvent('#regSubmit','tap',this.page.regPage,'submit');
    this.bindEvent('#chooseMale','tap',this.page.regPage,'chooseSex',1);
    this.bindEvent('#chooseFemale','tap',this.page.regPage,'chooseSex',0);
    this.bindEvent('#confirmNo','tap',this,'hideConfirm');
    this.bindEvent('#logoutButton','tap',this.user,'logout',1);
    this.bindEvent('#userInfoItemName','tap',this.page.inputPage,'showInput','name');
    this.bindEvent('#putQuestionButton','tap',this,'showPage','putQuestionPage');
    this.bindEvent('#makeTeamButton','tap',this,'showPage','makeTeamPage');
    this.bindEvent('#putQuestionAddChoiceButton','tap',this.page.putQuestionPage,'addChoice');
    this.bindEvent('#putQuestionDeleteChoiceButton','tap',this.page.putQuestionPage,'deleteChoice');
    this.bindEvent('#submitPutQuestionButton','tap',this.page.putQuestionPage,'submit');
    this.bindEvent('#makeTeamAddChoiceButton','tap',this.page.makeTeamPage,'addChoice');
    this.bindEvent('#makeTeamDeleteChoiceButton','tap',this.page.makeTeamPage,'deleteChoice');
    this.bindEvent('#submitMakeTeamButton','tap',this.page.makeTeamPage,'submit');
    this.bindEvent('#refreshResultButton','tap',this.page.lookQuestionPage,'refreshChoices');
    this.bindEvent('#doQuestionButton','tap',this.page.lookQuestionPage,'doQuestion');
    this.bindEvent('#showResultButton','tap',this.page.lookQuestionPage,'stopAndShowResult');
    jQuery('input').bind('focus',function(){
      pie.inputFocus(this);
    });
    jQuery('textarea').bind('focus',function(){
      pie.inputFocus(this);
    });
    jQuery('input').bind('blur',function(){
      pie.inputBlur(this);
    });
    jQuery('textarea').bind('blur',function(){
      pie.inputBlur(this);
    });
    jQuery('#userAvatarInput').bind('change',function(){
      pie.page.settingPage.uploadPhoto(this.files);
    });
  },
  bindEvent:function(ele,event,context,callback,arg){
    Quo(ele).bind(event,function(){
      if(arg != undefined){
        context[callback](arg,this.id);
      }
      else{
        context[callback](this.id);
      }
    });
  },
  showPage:function(pageId){
    if(this.curPageId == pageId){return;}
    jQuery('#'+this.curPageId+'LeftMenu').css('display','none');
    jQuery('#'+this.curPageId+'RightMenu').css('display','none');
    jQuery('#'+this.curPageId).css('display','none');
    this.curPageId = pageId;
    jQuery('#'+this.curPageId+'LeftMenu').css('display','block');
    jQuery('#'+this.curPageId+'RightMenu').css('display','block');
    jQuery('#'+this.curPageId).css('display','block');
    var curPage = this.page[this.curPageId];
    var pageHeight = this.height;
    if(curPage.headerExist){
      pageHeight -= this.headerHeight;
      jQuery('#pageTitle').html(curPage.title);
      jQuery('#pageLeftMenu').html(curPage.leftMenu);
      jQuery('#pieHeader').css('display','block');
    }
    else{
      jQuery('#pieHeader').css('display','none');
    }
    jQuery('#'+this.curPageId).css('height',pageHeight);
    if(curPage.needScroll){
      if(!curPage.scrollArea){
        if(curPage.needRefresh){
          curPage.scrollArea = new iScroll(pageId,{
            useTransition:true,
            topOffset:50,
            hScroll:false,
            checkDOMChanges:false,
            onScrollMove: function () {
              if(this.y < 0){pie.refreshReady = false;return;}
              if(this.y > 5&&pie.refreshReady){
                jQuery('#'+pie.curPageId+' .refreshIcon i').css('-webkit-transform','rotate(180deg)');
                jQuery('#'+pie.curPageId+' .refreshText').html('松开即可刷新');
                this.minScrollY = 0;
              }
              else if(this.y <=5&&!pie.refreshReady){
                pie.refreshReady = true;
                jQuery('#'+pie.curPageId+' .refreshText').html('下拉可以刷新');
                this.minScrollY = -50; 
              }
            },
            onScrollEnd: function () {
              if (this.y>=0&&pie.refreshReady) {
                jQuery('#'+pie.curPageId+' .refreshText').html('正在刷新');     
                pie.startRefresh();
              }
            }
          })
        }
        else{
          curPage.scrollArea = new iScroll(pageId,{
            useTransition:true,
            hScroll:false,
            checkDOMChanges:false
          })
        }
      }
      else{
        curPage.scrollArea.refresh();
      }
    }
    curPage.init();
  },
  startRefresh:function(){
    this.refreshStart = true;
    this.refreshReady = false;
    if(this.page[this.curPageId].needRefresh){
      jQuery('#'+this.curPageId+' .refreshIcon i').removeClass('fa-arrow-down');
      jQuery('#'+this.curPageId+' .refreshIcon i').addClass('fa-spin fa-spinner');
      this.page[this.curPageId].refresh();
    }
  },
  endRefresh:function(){
    this.refreshStart = false;
    this.refreshReady = false;
    var curTime = new Date();
    var month = curTime.getMonth()+1;
    if(month<10){
      month = '0'+month;
    }
    var date = curTime.getDate();
    if(date<10){
      date = '0'+date;
    }
    var hour = curTime.getHours();
    if(hour<10){
      hour = '0'+hour;
    }
    var minute = curTime.getMinutes();
    if(minute<10){
      minute = '0'+minute;
    }
    var timeHtml = '更新于: '+month+'-'+date+' '+hour+':'+minute;
    jQuery('#'+this.curPageId+' .refreshIcon i').removeClass('fa-spin fa-spinner');
    jQuery('#'+this.curPageId+' .refreshIcon i').addClass('fa-arrow-down');
    jQuery('#'+this.curPageId+' .refreshIcon i').css('-webkit-transform','rotate(0deg)');
    jQuery('#'+this.curPageId+' .refreshText').html('刷新成功');
    jQuery('#'+this.curPageId+' .refreshTime').html(timeHtml);
    setTimeout(function(){
      pie.page[pie.curPageId].scrollArea.refresh();
    },100);
  },
  pageBack:function(){
    if(this.loadingShow){
      this.hideLoading();
      return;
    }
    if(this.confirmShow){
      return;
    }
    var curBackPageId = this.page[this.curPageId].backPageId;
    if(curBackPageId){
      this.showPage(curBackPageId);
    }
  },
  messageTime:function(){
    var curTime = new Date();
    var year = curTime.getFullYear();
    var month = curTime.getMonth()+1;
    if(month<10){
      month = '0'+month;
    }
    var date = curTime.getDate();
    if(date<10){
      date = '0'+date;
    }
    var hour = curTime.getHours();
    if(hour<10){
      hour = '0'+hour;
    }
    var minute = curTime.getMinutes();
    if(minute<10){
      minute = '0'+minute;
    }
    var second = curTime.getSeconds();
    if(second<10){
      second = '0'+second;
    }
    var result = year+'-'+month+'-'+date+' '+hour+':'+minute+':'+second;
    return result;
  },
  inputFocus:function(elem){
    if(this.onInput){return;}
    this.curInputId = elem.id;
    this.onInput = true;
  },
  inputBlur:function(){
    this.onInput = false;
    this.curInputId = null;
    jQuery('#pie').css('top',0);
  },
  showShadow:function(){
    jQuery('#pieShadow').css('display','block');
  },
  hideShadow:function(){
    jQuery('#pieShadow').css('display','none');
  },
  showLoading:function(info){
    this.showShadow();
    this.loadingShow = true;
    jQuery('#pieLoading').css('top',Math.floor((pie.height-102)/2));
    jQuery('#loadingInfo').html(info);
    jQuery('#pieLoading').css('display','block');
    clearTimeout(this.loading);
    this.loading = setTimeout(function(){
      pie.hideLoading();
      pie.remind('加载失败,网络不给力啊...')
    },30000);
  },
  hideLoading:function(){
    this.hideShadow();
    clearTimeout(this.loading);
    this.loadingShow = false;
    jQuery('#pieLoading').css('display','none');
  },
  upload:function(path){
    pie.showLoading('正在上传')
    var ft = new FileTransfer();
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=path.substr(path.lastIndexOf('/')+1);
    options.mimeType="image/jpeg";
    var params = {};
    params.token = pie.user.data.access_token;
    options.params = params;
    var uploadUrl = pie.serverBase+'/api/rest/users/'+pie.user.data.puid+'/photos.json';
    ft.upload(path, uploadUrl, win, fail, options);
    function win(reply) {
      pie.hideLoading();
      var pieReply = JSON.parse(reply.response);
      if(pieReply.status == 'success'){
        pie.user.getInfo(0); 
      }
      else{
        pie.remind('上传文件失败,原因可能是:'+pieReply.message);
      }
    }
    function fail(error) {
      pie.hideLoading();
      pie.remind('上传文件失败,这应该是网络问题造成的');
    }
  },
  getPicture:function(type){
    navigator.camera.getPicture(onSuccess, onFail, {
      quality:50,
      destinationType:Camera.DestinationType.FILE_URI,
      sourceType:type,
      correctOrientation:true
    });
    function onSuccess(imageURI){
      jQuery('#uploadPhotoSelect').val(-1);
      pie.upload(imageURI);
      navigator.camera.cleanup();
    }
    function onFail(message){
      jQuery('#uploadPhotoSelect').val(-1);
    }
  },
  remind:function(content){
    var itemId = 'pieRemind';
    jQuery('#'+itemId+' td').html(content);
    jQuery('#'+itemId).css('display','block');
    if(this.remindDisapear){
      clearTimeout(this.remindDisapear);
    }
    this.remindDisapear = setTimeout(function(){
      jQuery('#'+itemId).fadeOut(2500);
    },1000);
  },
  confirm:function(content,callback){
    var height = jQuery('#pieConfirm').height()+100;
    jQuery('#pieConfirm').css('top',Math.floor((pie.height-height)/2));
    this.showShadow();
    this.confirmShow = true;
    jQuery('#pieConfirm').css('display','block');
    jQuery('#confirmContent').html(content);
    Quo('#confirmYes').unbind('tap');
    Quo('#confirmYes').bind('tap',function(){
      pie.hideConfirm();
      callback();
    });
  },
  hideConfirm:function(){
    pie.confirmShow = false;
    pie.hideShadow();
    jQuery('#pieConfirm').css('display','none');
  }
}
function init(){
  if('devicePixelRatio' in window){
    pie.dpi = window.devicePixelRatio;
  }
  if(typeof(cordova) == 'undefined'){
    if(document.domain == 'localhost'||document.domain == '127.0.0.1'){
      pie.isTeacher = true;
    }
    pie.serverBase = 'http://'+document.domain;
    jQuery('#uploadPhotoForm').css('display','block');
    pie.init();
  }
  else{
    document.addEventListener("deviceready", function(){
      document.addEventListener("backbutton",function(){
        if(pie.page[pie.curPageId].backPageId){
          pie.pageBack();
        }
        else{
          pie.confirm('确认要退出么?',function(){
            navigator.app.exitApp();
          });
        }
      },false);
      pie.init();
    }, false);
  }
}
function getType(o) { 
  var _t; 
  return ((_t = typeof(o)) == "object" ? o==null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase(); 
}
function dfsObject(obj){
  var curType = getType(obj);
  var outPut = '';
  if(curType == 'object'||curType == 'array'){
    for(var key in obj){
      console.log('\n'+key+' : '+dfsObject(obj[key]));
    }
  }
  else{
    return obj;
  }
}
function myEncode(str){
  if(str.length<1){return 'are you kidding me?';}
  var ret = str.charCodeAt(0).toString(20);
  for(var i = 1; i < str.length; i++){
    ret += ','+str.charCodeAt(i).toString(20);
  }
  return ret;
}
function myDecode(str){
  if(!str||!str.split){return 'are you kidding me';}
  var array = str.split(',');
  if(array.length<1){return 'are you kidding me?';}
  var ori = '';
  for(var i = 0; i < array.length; i++){
    ori += String.fromCharCode(parseInt(array[i],20))
  }
  return ori;
}
function diffArray(a,b){
  //求a和b的差异集合,即a-b
  if((getType(a) != 'array')||(getType(b) != 'array')){return null;}
  var aNum = a.length;
  var bNum = b.length;
  if(aNum<bNum){return null;}
  var ret = [];
  var tmp = [];
  for(var i = 0; i < bNum; i++){
    tmp[b[i]] = true;
  }
  for(var i = 0; i < aNum; i++){
    if(!tmp[a[i]]){
      ret.push(a[i]);
    }
  }
  return ret;
}
Array.prototype.find = function(ele){
  var len = this.length;
  for(var i = len; i >= 0; i--){
    if(this[i] == ele){
      return i;
    }
  }
  return -1;
}
$(document).ready(init);